import _ from 'lodash';
import localStorage from './storage';

const hasOwnProperty = Object.prototype.hasOwnProperty;
const BASE_URL = 'http://app.zazn.cn/';

function isLogin() {
  return localStorage('abra').get();
}

function has(object, key) {
  return object != null && hasOwnProperty.call(object, key);
}

// 校验图片
function isImg(value) {
  const reg = /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/;
  return reg.test(value);
}
// 字符处理
function lpad(str, len, pad = ' ') {
  str += '';
  while (str.length < len) {
    str = pad + str;
  }
  return str;
}
// 生成时间
function durationText(duration) {
  const minutes = Math.round(duration / 60);
  const seconds = Math.round(duration % 60);
  const timeStr = `${lpad(minutes, 2, '0')}:${lpad(seconds, 2, '0')}`;
  return timeStr;
}

function isObject(value) {
  const type = typeof value;
  return value != null && (type === 'object' || type === 'function');
}

function previewHtml(id, share = false) {
  const shareParam = share ? '&share=1' : '';
  // TODO: 后期优化
  return `${BASE_URL}cms/articleDetail_Html?id=${id}${shareParam}`;
}
const detailHtml = async (id) => {
  const res = await localStorage('abra').get();
  const { clientId, token } = res;
  return `${BASE_URL}cms_client/articleDetailForClient_Html?id=${id}&clientId=${clientId}&token=${token}`;
};
// 获取文件名生成对应的分享图片
function toShareImg(url) {
  let rooutImg = 'https://mmbiz.qlogo.cn/mmbiz_png/Mlg4ic5eWicWpZUbCksM6LicJgeq2EvibHNQzibTYY4w0DVOcIOC2eWsqibKpR8iceM5FAPiaVicoC71YsEibPrLib6zP6AZw/0?wx_fmt=png';
  if (url) {
    const name = _.last(_.split(url, '/'));
    rooutImg = `${BASE_URL}/qiniu_thumb/${name}`;
  }
  return rooutImg;
}

export default {
  has,
  isLogin,
  isImg,
  isObject,
  previewHtml,
  detailHtml,
  toShareImg,
  durationText,
};
